var xml2js 		= require('xml2js');
var AV 				= require('leanengine');
var Buffer 		= require("buffer").Buffer;
/*
	函数库
*/
exports.appID				= "wx4c4b76395337383e"//
exports.appsecret		= "5906410dfd1213b6693b805053873c18"//
exports.access_token= "";
exports.ticket			= "";
exports.deadline		= 0;
exports.noncestr		= "benibaby";
exports.code				= "";
exports.mch_id			= "1386458802";//微信支付商户号

var avOrderList 	= AV.Object.extend("OrderList");
/**
 * 获取access_token
 * 2015.09.28  by 胡斌
 * @param callback 		回调函数
 */
exports.getToken = function(onSuccess,onError) {
	var timestamp = Date.parse(new Date())/1000;
	if(timestamp<exports.deadline){
		onSuccess();
	}else{
		AV.Cloud.httpRequest({
			url: 'https://api.weixin.qq.com/cgi-bin/token',
			params: {
				grant_type	: 'client_credential',
				appid 		: exports.appID,
				secret 		: exports.appsecret,
			},
			success: function(res){
				exports.access_token	= res.data.access_token;
				exports.deadline		= timestamp+res.data.expires_in-1000;
				exports.ticket			= "";
				onSuccess();
			},
			error: function(res){
				onError(res.data);
			}
		});
	}
}


/**
 * 获取jsapi_ticket
 * 2015.10.14  by 胡斌
 * @param callback 		回调函数
 */
exports.getTicket = function(onSuccess,onError) {
	var timestamp = Date.parse(new Date())/1000;

	if(exports.ticket.length>1 && timestamp<exports.deadline){
		onSuccess();
	}else{
		exports.getToken(function(){
			AV.Cloud.httpRequest({
				url: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
				params: {
					access_token: exports.access_token,
					type 		: 'jsapi'
				},
				success: function(res){
					//console.dir(res.data);
					exports.ticket	= res.data.ticket;
					onSuccess();
				},
				error: function(res){
					onError(res.data);
				}
			});
		},function(data){
			//console.dir(res);
			//if(res.data)
			onError(data);
		});
	}
}


/**
 * 获取signature
 * 2015.10.14  by 胡斌
 * @param timestamp 时间戳
 */
exports.getSignature = function(timestamp,url) {
	var crypto 		= require('crypto');
	var shasum 		= crypto.createHash('sha1');
	shasum.update("jsapi_ticket="+exports.ticket+"&noncestr="+exports.noncestr+"&timestamp="+timestamp+"&url="+url);
	//console.log(url);

	return shasum.digest('hex');
}

/**
 * 获取access_token
 * 2015.09.28  by 胡斌
 * @param callback 		回调函数
 */
exports.getUserInfo = function(user){
	exports.getToken(function(){
	var authData=user.get("authData");
		AV.Cloud.httpRequest({
			url: 'https://api.weixin.qq.com/cgi-bin/user/info',
			params: {
				lang		: 'zh_CN',
				access_token: exports.access_token,
				openid 		: authData.weixin.openid,
			},
			success: function(res){
				user.set("nickname",res.data.nickname);
				user.set("sex",res.data.sex);
				user.set("city",res.data.city);
				user.set("province",res.data.province);
				user.save();

				if(res.data.headimgurl){
					var file = AV.File.withURL('headimg_'+res.data.openid+'.jpg', res.data.headimgurl);
					file.save().then(function(file) {
						user.set("headimg",file);
						user.save();
					});
					AV.Cloud.httpRequest({ url: res.data.headimgurl }).then(function(response) {
						var file = new AV.File('headimg_'+res.data.openid+'.jpg',response.buffer);
						file.save().then(function(file) {
							user.set("headimg",file);
							user.save();
						});
					});
				}
			},
			error: function(res){}
		});
	},function(err){
		console.error(err);
	})
}

/**
 * 微信认证
 * 2015.09.28  by 胡斌
 */
exports.checkUrl = function(req,res){
	//console.log("1111");
	var crypto 		= require('crypto');
	var shasum 		= crypto.createHash('sha1');
	var signature 	= req.query.signature
       ,timestamp 	= req.query.timestamp
       ,nonce 		= req.query.nonce
	   ,echostr 	= req.query.echostr;
	var tmpArr		= [timestamp,nonce,'benibaby'];
	var newArr		= tmpArr.sort();
	var tmpStr		= newArr.join('');

	shasum.update(tmpStr);
	if(shasum.digest('hex')===signature){
		res.send(echostr);
	}else{
		res.send("error");
	}
}

/**
 * 计算签名
 * 2015.11.03  by 胡斌
 */
exports.getSign = function(json){
	var crypto 	= require('crypto');
	var md5 	= crypto.createHash('md5');
	var stringA="",arr=[],sign;
	for(key in json){
		arr.push(key);
	}
	arr.sort();
	for(var i=0;i<arr.length;i++){
		arr[i]+="="+json[arr[i]];
	}
	stringA=arr.join("&");
	//console.log(stringA);

	stringSignTemp	= stringA+"&key="+exports.appsecret;

    var buf = new Buffer(stringSignTemp);
    var str = buf.toString("binary");
	//console.log(str);
	md5.update(str);
	var sign=md5.digest('hex').toUpperCase();
	//console.log(sign);
	return sign;
	//return stringSignTemp;
}

/**
 * 微信支付结果接收
 * 2015.11.06  by 胡斌
 */
exports.wxQRCallback = function(req, res) {
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function(chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function() {
		var parseString = xml2js.parseString;
		parseString(req.rawBody,{explicitArray : false}, function(err, data) {
			console.log(data);
			var queryOrderList		= new AV.Query(avOrderList);
			queryOrderList.equalTo("objectId",data.product_id);
			queryOrderList.first().then(function(result){
				console.log(result.id);
				var OrderList	=	result;
				var builder 	= new xml2js.Builder();  // JSON->xml
				var data={},json={};
				var json={};

				json['appid']			= exports.appID;
				json['body']			= "BeniBaby订单支付："+result.get("SN");
				json['mch_id']		= exports.mch_id;
				json['total_fee']	= 1;
				json['trade_type']				= "NATIVE";
				json['nonce_str']					= exports.id;
				json['openid']						= data.openid;
				json['notify_url']				= "http://www.benibaby.com/wx/pcb";
				json['out_trade_no']			= result.get("SN");
				json['spbill_create_ip']	= result.get("ip");
				json['product_id']				= result.id;
				json['sign']							= exports.getSign(json);
				data['xml']								= json;

				console.log(data);
				var xml	=  builder.buildObject(data);
				var request = require('request');
				var options = {
					headers: {'Content-Type':'text/xml; charset=utf-8'},
					url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
					method: 'POST',
					body: xml
				}
				request.post(options,function (error, response, body) {
					var parseString = xml2js.parseString;
					parseString(body,{explicitArray : false}, function(err, data) {
						console.log(data);
						if(data.xml.return_code=="FAIL"){
							console.error(data.xml.return_msg);
						}else if(data.xml.err_code_des){
							console.error(data.xml.err_code_des);
						}else{
							OrderList.set("wxPrepayId",data.xml.prepay_id);
							OrderList.set("wxPayData",data.xml);
							OrderList.save();
						}
					});
				});
			},function(error) {
				console.error(error);
			});/**/
		});
	});
}

/**
 * 微信支付结果接收
 * 2015.11.06  by 胡斌
 */
exports.wxPayCallback = function(req, res) {
	req.rawBody = '';
	req.setEncoding('utf8');
	req.on('data', function(chunk) {
		req.rawBody += chunk;
	});
	req.on('end', function() {
		var parseString = xml2js.parseString;
		parseString(req.rawBody,{explicitArray : false}, function(err, data) {
			console.dir(data);
		});
	});
}
